#!/bin/sh

# /etc/rc.d/rc.ntop : start/stop/restart ntop
# usage: ./rc.ntop { start | stop | restart }

# Thanks to andarius <andarius@errantnutron.com> for donating
# time and the various cleanups in the script and the start|stop|restart
# functions.

NTOPUID=@NTOPUSER@
NTOPGID=@NTOPGROUP@
NTOPLOG=/var/log/ntop
DATE=$(date +%a\ %b\ %d\ %T\ %Y)
RETVAL=0

# Sanity Checking
if [  ! -r "/var/lib/ntop/ntop_pw.db" ]; then
    echo "Can not read ntop password database. Exiting..."
    exit 1
fi

ntop_start() {
    echo -n $"Starting ntop ...  "
    if [ -r /var/run/ntop.pid ]; then
        if $(! /sbin/pidof ntop > /dev/null 2>&1 ) ; then
            echo "Removing an old /var/run/ntop.pid"
            rm -f /var/run/ntop.pid
        fi
    fi
    /usr/bin/ntop --w3c -u $NTOPUID -d >> $NTOPLOG 2>&1
    RETVAL=$?

    if [ $RETVAL -eq 0 ]; then
        touch /var/lock/ntop
        sleep 2
        echo "Done"
    else
        echo "Failed"
    fi
    return $RETVAL
}

ntop_stop() {
    echo -n $"Stopping ntop ...  "
    RETVAL=$?
    if [ $RETVAL -eq 0 ]; then
        if [ -r /var/run/ntop.pid ]; then
            killall ntop
            # Give it some time to die gracefully
            for second in 0 1 2 3 4 5 6 7 8 9 10 ; do
                if $(! /sbin/pidof ntop > /dev/null 2>&1 ) ; then
                    # ntop is a dirty little daemon:
                    rm -f /var/run/ntop.pid
                    break
                fi
                sleep 1
            done

            if [ "$second" = "10" ]; then
                echo "\nWARNING: ntop did not exit!"
                sleep 10
            else
                # Yes there are two spaces as this is the way ntop writes
                # their logfiles.
                echo "$DATE  EXIT: ntop stopped by user: $USER (UID: $EUID)" >> $NTOPLOG
                echo "Done"
            fi
        fi
        rm -f /var/lock/ntop
    fi
    return $RETVAL
}

# Lets see how we are being called:
case "$1" in
    start)
        ntop_start
        ;;
    stop)
        ntop_stop
        ;;
    restart|reload)
        ntop_stop
        # Takes a few to recover and be able to start again:
        sleep 10
        ntop_start
        ;;
    *)
        echo ""
        echo "Usage: $(basename $0) {start | stop | restart }"
        RETVAL=1
esac

exit $RETVAL
#EOF
